#include "tcpServer.hpp"
#include <memory>

using namespace std;

void Usage(string proc)
{
    cout << "Usage:\n\t" << proc << "serverport" << endl;
}

void calculate(int x, int y, char op, Response& res)
{
    res._exitcode = res._result = 0;
    switch (op)
    {
    case '+':
        res._result = x + y;
        break;
    case '-':
        res._result = x - y;
        break;
    case '*':
        res._result = x * y;
        break;
    case '/':
        if (y == 0)
        {
            res._exitcode = DIV_ZERO;
            return;
        }
        res._result = x / y;
        break;
    case '%':
        if (y == 0)
        {
            res._exitcode = MOD_ZERO;
            return;
        }
        res._result = x % y;
        break;
    default:
        res._exitcode = OP_ERR;
        break;
    }
}

void handlerMessage(Connection* conn)
{
    string onePackage;
    while (recvOnePackage(conn->_inbuffer, &onePackage))
    {
        string req_str;
        if (!deLength(onePackage, &req_str))
            return;
        Request req;
        if (!req.deserialize(req_str))
            return;
        
        cout << "#client: " << req._x << " " << req._op << " " << req._y << " = ?" << endl;

        Response res;
        calculate(req._x, req._y, req._op, res);

        string res_str;
        res.serialize(&res_str);
        string resPackage;
        enLength(res_str, &resPackage);
        conn->_outbuffer += resPackage;//outbuffer每次接收一个完整报文
    }
    if (conn->_outbuffer.size() && conn->_sender)
        conn->_sender(conn);
}

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);
    unique_ptr<tcpServer> svr(new tcpServer(port, handlerMessage));
    svr->initServer();
    svr->startServer();

    return 0;
}
